﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Routing;
using System.Web.Security;
using System.Security;
using System.Web.Compilation;

namespace Web.Ajax.Routing
{
	public interface IRoutablePage
	{
		RequestContext RequestContext { set; }
	}

	public class PageRoute : IRouteHandler
	{
		public PageRoute(string virtualPath)
			: this(virtualPath, true)
		{
		}

		public PageRoute(string virtualPath, bool checkPhysicalUrlAccess)
		{
			this.VirtualPath = virtualPath;
			this.CheckPhysicalUrlAccess = checkPhysicalUrlAccess;
		}

		public string VirtualPath { get; private set; }

		public bool CheckPhysicalUrlAccess { get; set; }

		public IHttpHandler GetHttpHandler(RequestContext requestContext)
		{
			if (this.CheckPhysicalUrlAccess
			  && !UrlAuthorizationModule.CheckUrlAccessForPrincipal(this.VirtualPath
					  , requestContext.HttpContext.User
					  , requestContext.HttpContext.Request.HttpMethod))
				throw new SecurityException();

			var page = BuildManager
			  .CreateInstanceFromVirtualPath(this.VirtualPath
				, typeof(Page)) as IHttpHandler;

			if (page != null)
			{
				var routablePage = page as IRoutablePage;
				if (routablePage != null)
					routablePage.RequestContext = requestContext;
			}
			return page;
		}

		public static Route Map(string url, string resource)
		{
			return new Route(url, new PageRoute(resource));
		}
	}
}
